# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import urllib.request


# 如果想使用管道的话, 就要在 settings.py 中开启管道
class DangdangPipeline:
    # 爬虫文件开始之前执行的方法
    def __init__(self):
        self.fp = None

    def open_spider(self, spider):
        self.fp = open('book.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        # """
        # 下载数据
        # 以下模式不推荐  因为文件操作太频繁
        # :param item: yield 后返回的 book 对象
        # :param spider:
        # :return:
        # """
        # # 1.write 只能保存一个字符串
        # with open('book.json', 'a', encoding='utf-8') as f:
        #     f.write(str(item))
        self.fp.write(str(item))
        return item

    # 爬虫文件结束之前执行的方法
    def close_spider(self, spider):
        self.fp.close()


class DangDangDownload:
    """
    1.定义管道类
    2.在 settings 中开启管道
        "dangdang.pipelines.DangDangDownload": 301,
    """
    def process_item(self, item, spider):
        url = 'https:'+item.get('src')
        fileName = './books/'+item.get('name')+'.jpg'
        urllib.request.urlretrieve(url=url, filename=fileName)

        return item
